package com.hoshiicloud.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.constant.DeleteStatusEnum;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.query.OmnipotentParam;
import com.hoshiicloud.common.query.OmnipotentWrapper;
import com.hoshiicloud.common.update.UpdateBatchParam;
import com.hoshiicloud.goods.component.GoodsProFileComponent;
import com.hoshiicloud.goods.entity.sku.BaseSku;
import com.hoshiicloud.goods.entity.sku.ProductManage;
import com.hoshiicloud.goods.entity.spu.ExtSpu;
import com.hoshiicloud.goods.feign.IdGeneratorService;
import com.hoshiicloud.goods.mapper.sku.ProductManageMapper;
import com.hoshiicloud.goods.param.sku.BranchStoreProductPageParam;
import com.hoshiicloud.goods.service.ExtSpuService;
import com.hoshiicloud.goods.service.ProductManageService;
import com.hoshiicloud.goods.vo.BranchStoreGoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品sku分配 服务实现类
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-04
 */
@Slf4j
@Service
public class ProductManageServiceImpl extends ServiceImpl<ProductManageMapper, ProductManage> implements ProductManageService {
    private final IdGeneratorService idGeneratorService;
    private final ProductManageMapper productManageMapper;
    public ProductManageServiceImpl(IdGeneratorService idGeneratorService, ProductManageMapper productManageMapper) {
        this.idGeneratorService = idGeneratorService;
        this.productManageMapper = productManageMapper;
    }

    @Override
    @Logable(authName = "(product-manage)-分页查询商品sku分配")
    @Cacheable(cacheNames = "ProductManage", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public Page<ProductManage> getPage(Page<ProductManage> page, Wrapper<ProductManage> queryWrapper, String key) {
        baseMapper.selectPage(page, queryWrapper);
        return page;
    }

    @Override
    @Logable(authName = "(product-manage)-查询商品sku分配列表")
    @Cacheable(cacheNames = "ProductManage", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public List<ProductManage> listByParam(QueryWrapper<ProductManage> queryWrapper, String key) {
        return baseMapper.selectList(queryWrapper);
    }


    @Override
    @Cacheable(cacheNames = "ProductManage", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "(product-manage)-根据id查询商品sku分配 ")
    public ProductManage getById(Long id) {
        return baseMapper.selectById(id);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "ProductManage", allEntries = true)
    @Logable(authName = "(product-manage)-新增商品sku分配")
    public boolean save(ProductManage entity) {
        LocalDateTime time = LocalDateTime.now();
        // 主键ID生成
        String id = idGeneratorService.queryGeneratorId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException(CommonError.error("主键ID生成失败"));
        }
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(time);
        entity.setUpdatedTime(time);
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return true;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "ProductManage", allEntries = true)
    @Logable(authName = "(product-manage)-修改商品sku分配")
    public boolean updateById(ProductManage entity) {
        entity.setUpdatedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "ProductManage", allEntries = true)
    @Logable(authName = "(product-manage)-删除商品sku分配")
    public boolean deleteById(Long id) {
        ProductManage entity = new ProductManage();
        entity.setId(id);
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setDeleted(DeleteStatusEnum.DELETED.getCode());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除失败"));
        }
        return true;
    }

    @Override
    @Cacheable(cacheNames = "ProductManage", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "(product-manage)-根据id集合查询商品sku分配")
    public List<ProductManage> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }

    /**
     * 分页查询分店商品信息
     */
    @Override
    @Logable(authName = "商品管理-商品sku分配管理-分页查询分店商品列表")
    public Page<BranchStoreGoodsVo> listBranchStoreGoodsByStoreId(BranchStoreProductPageParam param) {
        Page<BranchStoreGoodsVo> page = new Page(Long.valueOf(param.getPageNumber()),Long.valueOf(param.getPageSize()));
        List<BranchStoreGoodsVo> branchs = productManageMapper.listBranchStoreGoodsByStoreId(page,param);
        for (BranchStoreGoodsVo branchStoreGoodsVo: branchs) {
            String[] images = branchStoreGoodsVo.getSpuImage().split(",");
            List<String> imageList = Arrays.asList(images);
            branchStoreGoodsVo.setSpuImageArr(imageList);
        }
        page.setRecords(branchs);
        return page;
    }
    @Override
    @Logable(authName = "商品管理-商品sku分配管理-根据店铺id 获取sku分配")
    public List<ProductManage> listByStoreId(Long storeId) {
        QueryWrapper<ProductManage> q = new QueryWrapper<>();
        q.lambda().eq(ProductManage::getStoreId,storeId).eq(ProductManage::getDeleted,0);
        return baseMapper.selectList(q);
    }

    @Override
    @CacheEvict(cacheNames = "ProductManage", allEntries = true)
    @Logable(authName = "商品管理-商品sku分配管理-批量保存")
    public Boolean saveBatch1(List<ProductManage> list) {
        return this.saveBatch(list);
    }

    @CacheEvict(cacheNames = "ProductManage", allEntries = true)
    @Logable(authName = "根据自定义条件批量更新")
    @Override
    public boolean updateBatchByWrapper(UpdateBatchParam<ProductManage> updateBatchParam) {
        ProductManage updateEntity = updateBatchParam.getUpdateEntity();
        QueryWrapper<ProductManage> wrapper = updateBatchParam.getWrapper();
        return this.update(updateEntity, wrapper);
    }

    /**
     * 批量更新
     */
    @CacheEvict(cacheNames = "ProductManage", allEntries = true)
    @Logable(authName = "批量更新")
    @Override
    public Boolean updateBatch(OmnipotentParam<ProductManage> param) {
        OmnipotentWrapper<ProductManage> wrapper = new OmnipotentWrapper<>();
        UpdateWrapper<ProductManage> updateWrapper = wrapper.getUpdateWrapper(param.getWrappers());
        ProductManage entity = param.getEntity();
        return this.update(entity, updateWrapper);
    }

}
